/**
 * 
 */
package com.sebscape.sebcms.slideshow.persistence;

import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.PhotoEntry;
import com.google.gdata.util.ServiceException;
import com.sebscape.sebcms.slideshow.domain.GenericSlideBean;
import com.sebscape.sebcms.slideshow.domain.GenericSlideShow;

/**
 * @author Stephen
 *
 */
public class SlideShowDao extends PicasaDao {

	private static Log log = LogFactory.getLog( SlideShowDao.class ); 
			
	private List<AlbumEntry> albums;
	
	/**
	 * @param serviceName
	 * @param uname
	 * @param passwd
	 */
	public SlideShowDao(String serviceName, String uname, String passwd) {
		super(serviceName, uname, passwd);
		initAlbumList();
	}

	/**
	 * @param uname
	 * @param passwd
	 */
	public SlideShowDao(String uname, String passwd) {
		super(uname, passwd);
		initAlbumList();
	}
	
	private void initAlbumList(){
		try {
			this.albums = getAlbums();
			log.debug( "initialized albums List size = " + albums );
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
	}
	
	public AlbumEntry getAlbumByName( String name ){
		log.debug( "albums = " + albums );
		log.debug( "seek name = " + name );
		if( albums != null ){
			for( AlbumEntry album: albums ){
				if( album.getTitle().getPlainText().equalsIgnoreCase( name ) ){
					return album;
				}
			}
		}
		return null;
	}

	public AlbumEntry getAlbumById( String id ){
		for( AlbumEntry album: albums ){
			if( album.getId().equalsIgnoreCase( id ) ){
				return album;
			}
		}
		return null;
	}
	
	public GenericSlideShow getSlideShow( String albumName ) throws IOException, ServiceException{
		GenericSlideShow show = new GenericSlideShow();
		if( super.getIsConnected() ){
			log.debug( "Fetching album for albumName = " + albumName );
			AlbumEntry album = this.getAlbumByName( albumName );
			log.debug( "Fetching photos for album = " + album );
			List<PhotoEntry> photos = this.getPhotos( album );
			for( PhotoEntry photo: photos ){
				GenericSlideBean slide = new GenericSlideBean( photo.getMediaContents().get(0).getUrl().toString() + "?imgmax=400" );
				if( photo.getWidth() > photo.getHeight() ){ // landscape
					show.getLandscapeSlides().add( slide );
				} else { // else is portrait.
					show.getPortraitSlides().add( slide );
				}
			}
		}
		return show;
	}

}
